package org.moflon.moca;

import java.io.File;

import org.apache.log4j.BasicConfigurator;
import org.moflon.moca.vhdl.parser.VhdlParserAdapter;
import org.moflon.moca.vhdl.unparser.VhdlUnparserAdapter;
import org.moflon.util.eMoflonEMFUtil;

import Moca.CodeAdapter;
import Moca.MocaFactory;
import MocaTree.Folder;
import MocaTree.MocaTreePackage;
import VHDLCodeAdapter.TreeToVHDL;
import VHDLCodeAdapter.VHDLCodeAdapterFactory;
import VHDLCodeAdapter.VHDLCodeAdapterPackage;
import VHDLCodeAdapter.VHDLToTree;
import VHDLModel.VHDLSpecification;

public class MocaMain {
	// public static final String inputModel =
	// "instances/in_model/CompositeBlock.vhdl.xmi";
	public static final String inputModel = "instances/out/test.vhdl.xmi";
	public static final String outputDir = "instances/out_text/";

	public static final String input = "instances/in";

	private static CodeAdapter codeAdapter;

	public static void main(String[] args) {
		BasicConfigurator.configure();

		// Register parsers and unparsers
		codeAdapter = MocaFactory.eINSTANCE.createCodeAdapter();
		codeAdapter.getParser().add(new VhdlParserAdapter());
		codeAdapter.getUnparser().add(new VhdlUnparserAdapter());
		
		// Text-to-model
		// textToModel();

		// Model-to-text
		modelToText();
	}

	private static void modelToText() {
		VHDLSpecification spec = (VHDLSpecification) eMoflonEMFUtil.loadModel(
				VHDLCodeAdapterPackage.eINSTANCE, inputModel, null);
		VHDLToTree transformer = VHDLCodeAdapterFactory.eINSTANCE
				.createVHDLToTree();
		MocaTree.File file = transformer.transform(spec);

		codeAdapter.unparseFile(file, new File(outputDir));

		// Save tree to file
		eMoflonEMFUtil.saveModel(MocaTreePackage.eINSTANCE, file,
				"instances/tree-backward.xmi");
	}

	private static void textToModel() {
		// Perform text-to-tree
		Folder tree = codeAdapter.parse(new File(input));

		// Save tree to file
		eMoflonEMFUtil.saveModel(MocaTreePackage.eINSTANCE, tree,
				"instances/tree-forward.xmi");

		// Perform tree-to-model
		TreeToVHDL transformer = VHDLCodeAdapterFactory.eINSTANCE
				.createTreeToVHDL();
		transformer.transform(tree);

		// Save model to file
		for (VHDLSpecification spec : transformer.getVhdlspecification()) {
			eMoflonEMFUtil.saveModel(VHDLCodeAdapterPackage.eINSTANCE, spec,
					"instances/out/" + spec.getName() + ".xmi");
		}
	}
}